import React, { useState, useEffect } from 'react';
import { Link, useLocation, Outlet } from 'react-router-dom';

interface NavItem {
  path: string;
  label: string;
  icon: string;
  children?: NavItem[]; // 添加子菜单属性
}

const navItems: NavItem[] = [
  { path: '/SideNav/kongzhi', label: '应用商城', icon: '🌤️' },
  { path: '/SideNav/shouye', label: '首页', icon: '🏠' },
  { path: '/SideNav/ai-chat', label: '智能创作', icon: '🤖' },
  { path: '/SideNav/apps', label: '应用库', icon: '📱' },
  // 爬虫工具作为一级菜单，包含子菜单
  { 
    path: '/SideNav/crawler', 
    label: '爬虫工具', 
    icon: '⏰',
    children: [
      { path: '/SideNav/alarm', label: '数据统计仪表盘', icon: '📊' },
      { path: '/SideNav/Dashboard', label: '数据看板', icon: '📈' },
      { path: '/SideNav/smart-video', label: '智能视频', icon: '🎥' }
    ]
  },
];

const SideNav: React.FC = () => {
  const location = useLocation();
  const [activePath, setActivePath] = useState(location.pathname);
  const [openMenus, setOpenMenus] = useState<Record<string, boolean>>({}); // 控制菜单展开状态

  useEffect(() => {
    setActivePath(location.pathname);
    
    // 如果当前路径是子菜单项，自动展开父菜单
    navItems.forEach(item => {
      if (item.children && item.children.some(child => activePath === child.path)) {
        setOpenMenus(prev => ({
          ...prev,
          [item.path]: true
        }));
      }
    });
  }, [location.pathname]);

  // 切换子菜单展开状态
  const toggleMenu = (path: string) => {
    setOpenMenus(prev => ({
      ...prev,
      [path]: !prev[path]
    }));
  };

  // 处理菜单点击事件
  const handleMenuClick = (path: string, hasChildren: boolean) => {
    if (hasChildren) {
      toggleMenu(path);
    } else {
      // 点击非爬虫工具的一级菜单时，收起爬虫工具的二级菜单
      setOpenMenus(prev => ({
        ...prev,
        '/SideNav/crawler': false
      }));
    }
  };

  return (
    <div style={{ display: 'flex', height: '100vh', width: '100%' }}>
      <div
        style={{
          width: '70px',
          height: '100vh',
          background: 'linear-gradient(to bottom, #ffd1dc, #ffb6c1)', // 渐变背景
          position: 'fixed',
          top: 0,
          left: 0,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          paddingTop: '20px',
          gap: '30px',
          zIndex: 1000,
          boxShadow: '2px 0 5px rgba(0,0,0,0.1)',
        }}
      >
        {navItems.map((item) => (
          <div key={item.path} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
            {item.children ? (
              // 有子菜单的项
              <Link
                to={item.path}
                onClick={(e) => {
                  e.preventDefault();
                  handleMenuClick(item.path, true);
                }}
                style={{
                  color: activePath === item.path || (item.children && item.children.some(child => activePath === child.path)) ? '#ffffff' : '#333333',
                  textDecoration: 'none',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  fontSize: '24px',
                  position: 'relative',
                  cursor: 'pointer',
                  background: activePath === item.path || (item.children && item.children.some(child => activePath === child.path)) ? 'rgba(217, 70, 239, 0.3)' : 'transparent',
                  borderRadius: '10px',
                  padding: '10px 0',
                  width: '80%',
                  transition: 'all 0.3s ease',
                }}
              >
                <span>{item.icon}</span>
                <span
                  style={{
                    fontSize: '12px',
                    marginTop: '4px',
                    color: activePath === item.path || (item.children && item.children.some(child => activePath === child.path)) ? '#ffffff' : '#333333',
                    fontWeight: activePath === item.path || (item.children && item.children.some(child => activePath === child.path)) ? 'bold' : 'normal',
                  }}
                >
                  {item.label}
                </span>
                {/* 子菜单展开/收起图标 */}
                <span style={{ 
                  position: 'absolute', 
                  right: '-5px', 
                  fontSize: '10px',
                  transition: 'transform 0.3s ease',
                  color: activePath === item.path || (item.children && item.children.some(child => activePath === child.path)) ? '#ffffff' : '#666666',
                  bottom: '5px',
                  transform: openMenus[item.path] ? 'rotate(180deg)' : 'rotate(0deg)',
                }}>
                  ▼
                </span>
              </Link>
            ) : (
              // 没有子菜单的项
              <Link
                to={item.path}
                onClick={() => {
                  // 点击非爬虫工具的一级菜单时，收起爬虫工具的二级菜单
                  setOpenMenus(prev => ({
                    ...prev,
                    '/SideNav/crawler': false
                  }));
                }}
                style={{
                  color: activePath === item.path ? '#ffffff' : '#333333',
                  textDecoration: 'none',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  fontSize: '24px',
                  position: 'relative',
                  cursor: 'pointer',
                  background: activePath === item.path ? 'rgba(217, 70, 239, 0.3)' : 'transparent',
                  borderRadius: '10px',
                  padding: '10px 0',
                  width: '80%',
                  transition: 'all 0.3s ease',
                }}
              >
                <span>{item.icon}</span>
                <span
                  style={{
                    fontSize: '12px',
                    marginTop: '4px',
                    color: activePath === item.path ? '#ffffff' : '#333333',
                    fontWeight: activePath === item.path ? 'bold' : 'normal',
                  }}
                >
                  {item.label}
                </span>
              </Link>
            )}
            
            {/* 渲染子菜单 - 默认收起，点击时展开 */}
            {item.children && (
              <div style={{ 
                display: 'flex', 
                flexDirection: 'column', 
                alignItems: 'center', 
                marginTop: '10px',
                gap: '10px',
                padding: openMenus[item.path] ? '10px 0' : '0',
                height: openMenus[item.path] ? 'auto' : '0',
                maxHeight: openMenus[item.path] ? '200px' : '0',
                overflow: 'hidden',
                // 将背景颜色修改为与其他一级菜单一致
                background: 'linear-gradient(to bottom, #ffd1dc, #ffb6c1)',
                borderRadius: '8px',
                width: '85%',
                boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                border: '1px solid rgba(217, 70, 239, 0.2)',
                transition: 'all 0.3s ease',
              }}>
                {item.children.map((child) => (
                  <Link
                    key={child.path}
                    to={child.path}
                    onClick={() => {
                      // 点击子菜单时收起爬虫工具的二级菜单
                      setOpenMenus(prev => ({
                        ...prev,
                        '/SideNav/crawler': false
                      }));
                    }}
                    style={{
                      color: activePath === child.path ? '#ffffff' : '#333333',
                      textDecoration: 'none',
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      fontSize: '16px',
                      padding: '8px 0',
                      width: '100%',
                      background: activePath === child.path ? 'rgba(217, 70, 239, 0.3)' : 'transparent',
                      borderRadius: '5px',
                      transition: 'all 0.2s ease',
                      opacity: openMenus[item.path] ? 1 : 0,
                      transform: openMenus[item.path] ? 'translateY(0)' : 'translateY(-10px)',
                    }}
                  >
                    <span>{child.icon}</span>
                    <span
                      style={{
                        fontSize: '10px',
                        marginTop: '2px',
                        color: activePath === child.path ? '#ffffff' : '#333333',
                        textAlign: 'center',
                        fontWeight: activePath === child.path ? 'bold' : 'normal',
                      }}
                    >
                      {child.label}
                    </span>
                  </Link>
                ))}
              </div>
            )}
          </div>
        ))}
      </div>
      <div style={{ marginLeft: '70px', flex: 1, overflowY: 'auto' }}>
        <Outlet />
      </div>
    </div>
  );
};

export default SideNav;